<template>
  <div class="work-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <el-segmented
            v-model="send"
            :options="[
              { label: '我发送的', value: 1 },
              { label: '我接收的', value: 0 },
            ]"
            @change="handleSegmentChange"
          />
          <el-button v-if="send == 1" type="primary" @click="showWorkModal">新增汇报</el-button>
        </div>
      </template>

      <el-form :model="searchForm" layout="inline" class="search-form">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.diffTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.types" style="width: 120px">
            <el-option value="" label="全部"></el-option>
            <el-option value="1" label="日报"></el-option>
            <el-option value="2" label="周报"></el-option>
            <el-option value="3" label="月报"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="send == 0" label="阅读状态">
          <el-select v-model="searchForm.read" style="width: 120px">
            <el-option value="" label="全部"></el-option>
            <el-option value="1" label="未读"></el-option>
            <el-option value="2" label="已读"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchWorks">搜索</el-button>
          <el-button style="margin-left: 8px" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :columns="send == 1 ? sendColumns : receiveColumns"
        :data="works"
        :pagination="pagination"
        @current-change="handleTableChange"
        row-key="id"
      >
        <template #default="{ column, row }">
          <template v-if="column.dataIndex === 'types'">
            <el-tag :type="getWorkTypeColor(row.types)">{{ getWorkTypeText(row.types) }}</el-tag>
          </template>
          <template v-else-if="column.dataIndex === 'read_time'">
            <el-tag :type="row.read_time ? 'success' : 'danger'">
              {{ row.read_time ? '已读' : '未读' }}
            </el-tag>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <el-space>
              <el-button type="text" @click="viewWork(row)">查看</el-button>
              <el-button v-if="send == 1" type="text" @click="editWork(row)">编辑</el-button>
              <el-button v-if="send == 1" type="text" @click="deleteWork(row.id)">删除</el-button>
            </el-space>
          </template>
        </template>
      </el-table>
    </el-card>

    <!-- 工作汇报编辑/新增模态框 -->
    <el-dialog
      v-model="workModalVisible"
      :title="editingWork.id ? '编辑汇报' : '新增汇报'"
      @close="closeWorkModal"
      width="600px"
    >
      <el-form :model="workForm" layout="vertical">
        <el-form-item label="汇报类型" required>
          <el-select v-model="workForm.types">
            <el-option value="1" label="日报"></el-option>
            <el-option value="2" label="周报"></el-option>
            <el-option value="3" label="月报"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="汇报日期" required>
          <el-date-picker v-if="workForm.types == '1'" v-model="workForm.startDate" type="date" />
          <el-date-picker
            v-else
            v-model="workForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="汇报对象" required>
          <el-select
            v-model="workForm.toUids"
            multiple
            placeholder="请选择汇报对象"
            :options="userOptions"
          />
        </el-form-item>
        <el-form-item label="工作内容" required>
          <el-input v-model="workForm.works" type="textarea" :rows="6" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeWorkModal">取消</el-button>
          <el-button type="primary" @click="saveWork">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 工作汇报详情抽屉 -->
    <el-drawer
      v-model="workDetailVisible"
      title="工作汇报详情"
      direction="rtl"
      :size="600"
      @close="closeWorkDetail"
    >
      <div class="drawer-content-wrapper">
        <el-skeleton :loading="detailLoading" :rows="8">
          <div class="info-section">
            <h3 class="section-title">工作汇报详情</h3>
            <div class="info-descriptions">
              <el-descriptions v-if="workDetail" :column="1">
                <el-descriptions-item label="汇报类型">
                  <el-tag :type="getWorkTypeColor(workDetail.types)">
                    {{ getWorkTypeText(workDetail.types) }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="汇报日期">
                  {{ workDetail.range_date }}
                </el-descriptions-item>
                <el-descriptions-item v-if="send == 1" label="汇报对象">
                  {{ workDetail.to_unames }}
                </el-descriptions-item>
                <el-descriptions-item v-else label="汇报人">
                  {{ workDetail.from_name }}
                </el-descriptions-item>
                <el-descriptions-item label="工作内容">
                  <div v-html="workDetail.works"></div>
                </el-descriptions-item>
                <el-descriptions-item v-if="send == 0" label="发送时间">
                  {{ workDetail.send_time }}
                </el-descriptions-item>
                <el-descriptions-item v-if="send == 0" label="阅读时间">
                  {{ workDetail.read_time || '未读' }}
                </el-descriptions-item>
                <el-descriptions-item label="创建时间">
                  {{ workDetail.create_time }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
        </el-skeleton>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { useOAStore } from '../../store/oa'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { Work } from '../../store/oa'
  import type { Dayjs } from 'dayjs'
  import dayjs from 'dayjs'

  const oaStore = useOAStore()

  // 发送/接收切换
  const send = ref(1)

  // 搜索表单
  const searchForm = reactive({
    diffTime: [] as Dayjs[],
    types: '' as string,
    read: '' as string,
  })

  // 表格列定义 - 发送的汇报
  const sendColumns = [
    {
      prop: 'types',
      label: '类型',
      width: 80,
    },
    {
      prop: 'start_date',
      label: '开始日期',
    },
    {
      prop: 'end_date',
      label: '结束日期',
    },
    {
      prop: 'files',
      label: '附件',
    },
    {
      prop: 'create_time',
      label: '创建时间',
    },
    {
      prop: 'action',
      label: '操作',
      width: 150,
    },
  ]

  // 表格列定义 - 接收的汇报
  const receiveColumns = [
    {
      prop: 'types',
      label: '类型',
      width: 80,
    },
    {
      prop: 'from_name',
      label: '汇报人',
    },
    {
      prop: 'start_date',
      label: '开始日期',
    },
    {
      prop: 'end_date',
      label: '结束日期',
    },
    {
      prop: 'files',
      label: '附件',
    },
    {
      prop: 'send_time',
      label: '发送时间',
    },
    {
      prop: 'read_time',
      label: '阅读状态',
      width: 80,
    },
    {
      prop: 'action',
      label: '操作',
      width: 150,
    },
  ]

  // 表格分页
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
  })

  // 工作汇报数据
  const works = ref<Work[]>([])

  // 工作汇报模态框
  const workModalVisible = ref(false)

  // 工作汇报详情抽屉
  const workDetailVisible = ref(false)

  // 详情加载状态
  const detailLoading = ref(false)

  // 编辑中的工作汇报
  const editingWork = ref<any>({})

  // 工作汇报详情
  const workDetail = ref<any>(null)

  // 工作汇报表单
  const workForm = reactive({
    id: 0,
    types: '1' as string,
    startDate: null as null | Dayjs,
    dateRange: [] as Dayjs[],
    toUids: [] as string[],
    works: '' as string,
  })

  // 用户选项（模拟数据）
  const userOptions = [
    { label: '张三', value: '1' },
    { label: '李四', value: '2' },
    { label: '王五', value: '3' },
  ]

  // 获取工作类型文本
  const getWorkTypeText = (type: number) => {
    const types: Record<number, string> = {
      1: '日报',
      2: '周报',
      3: '月报',
    }
    return types[type] || '未知'
  }

  // 获取工作类型颜色
  const getWorkTypeColor = (type: number) => {
    const colors: Record<number, string> = {
      1: 'primary',
      2: 'success',
      3: 'warning',
    }
    return colors[type] || 'default'
  }

  // 处理切换发送/接收
  const handleSegmentChange = (value: number) => {
    send.value = value
    pagination.currentPage = 1
    searchWorks()
  }

  // 搜索工作汇报
  const searchWorks = async () => {
    try {
      const params = {
        page: pagination.currentPage,
        limit: pagination.pageSize,
        send: send.value,
        diff_time:
          searchForm.diffTime.length > 0
            ? `${searchForm.diffTime[0].format('YYYY-MM-DD')}~${searchForm.diffTime[1].format('YYYY-MM-DD')}`
            : '',
        types: searchForm.types,
        read: send.value == 0 ? searchForm.read : undefined,
      }

      const res = await oaStore.getWorkListAction(params)
      if (res.code === 0) {
        works.value = res.data
        pagination.total = res.count
      }
    } catch (error) {
      ElMessage.error('获取工作汇报列表失败')
    }
  }

  // 重置搜索
  const resetSearch = () => {
    searchForm.diffTime = []
    searchForm.types = ''
    searchForm.read = ''
    pagination.currentPage = 1
    searchWorks()
  }

  // 处理表格分页变化
  const handleTableChange = (currentPage: number) => {
    pagination.currentPage = currentPage
    searchWorks()
  }

  // 显示工作汇报模态框
  const showWorkModal = () => {
    workModalVisible.value = true
    editingWork.value = {}
    workForm.id = 0
    workForm.types = '1'
    workForm.startDate = null
    workForm.dateRange = []
    workForm.toUids = []
    workForm.works = ''
  }

  // 编辑工作汇报
  const editWork = (record: any) => {
    workModalVisible.value = true
    editingWork.value = record

    workForm.id = record.id
    workForm.types = String(record.types)
    workForm.startDate = record.start_date ? dayjs(record.start_date) : null
    workForm.dateRange =
      record.start_date && record.end_date ? [dayjs(record.start_date), dayjs(record.end_date)] : []
    workForm.toUids = record.to_uids ? record.to_uids.split(',') : []
    workForm.works = record.works
  }

  // 查看工作汇报
  const viewWork = async (record: any) => {
    try {
      detailLoading.value = true
      workDetailVisible.value = true

      const params = {
        id: record.id,
        send: String(send.value),
      }

      const res = await oaStore.getWorkDetailAction(params)
      if (res.data.code === 0) {
        workDetail.value = res.data
      }
    } catch (error) {
      ElMessage.error('获取工作汇报详情失败')
    } finally {
      detailLoading.value = false
    }
  }

  // 保存工作汇报
  const saveWork = async () => {
    try {
      const params = {
        id: workForm.id,
        types: workForm.types,
        start_date:
          String(workForm.types) === '1'
            ? workForm.startDate
              ? workForm.startDate.format('YYYY-MM-DD')
              : ''
            : workForm.dateRange.length > 0
              ? workForm.dateRange[0].format('YYYY-MM-DD')
              : '',
        end_date:
          String(workForm.types) === '1'
            ? workForm.startDate
              ? workForm.startDate.format('YYYY-MM-DD')
              : ''
            : workForm.dateRange.length > 1
              ? workForm.dateRange[1].format('YYYY-MM-DD')
              : '',
        to_uids: workForm.toUids.join(','),
        works: workForm.works,
      }

      const res = await oaStore.saveWorkAction(params)
      if (res.data.code === 0) {
        ElMessage.success(res.data.msg || '保存成功')
        workDetailVisible.value = false
        searchWorks()
      } else {
        ElMessage.error(res.data.msg || '保存失败')
      }
    } catch (error) {
      ElMessage.error('保存工作汇报失败')
    }
  }

  // 关闭工作汇报模态框
  const closeWorkModal = () => {
    workModalVisible.value = false
  }

  // 关闭工作汇报详情抽屉
  const closeWorkDetail = () => {
    workDetailVisible.value = false
    workDetail.value = null
  }

  // 删除工作汇报
  const deleteWork = (id: number) => {
    ElMessageBox.confirm('确定要删除这个工作汇报吗？', '确认删除', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const res = await oaStore.deleteWorkAction(id)
          if (res.data.code === 0) {
            ElMessage.success(res.data.msg || '删除成功')
            searchWorks()
          } else {
            ElMessage.error(res.data.msg || '删除失败')
          }
        } catch (error) {
          ElMessage.error('删除工作汇报失败')
        }
      })
      .catch(() => {
        // 用户取消删除
      })
  }

  // 组件挂载时获取数据
  onMounted(() => {
    searchWorks()
  })
</script>

<style scoped>
  .work-container {
    padding: 16px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-bottom: 16px;
  }

  .drawer-content-wrapper {
    padding: 16px;
  }

  .info-section {
    width: 100%;
  }

  .section-title {
    font-size: 18px;
    margin-bottom: 16px;
  }

  .info-descriptions {
    width: 100%;
  }
</style>
